<template>
  <div class="search-result">
    <!-- 搜索结果 -->
    <van-list v-model="loading" :finished="finished" finished-text="没有更多了"
      @load="onLoad" :error.sync="error" error-text="请求失败，点击重新加载">
      <van-cell v-for="text in list" :key="text.art_id" :title="text.title" />
    </van-list>
  </div>
</template>

<script>
import { getSearchResult } from '@/api/search'
export default {
  name: 'SearchResult',
  components: {},
  props: {
    searchText: {
      type: String,
      require: true
    }
  },
  data () {
    return {
      list: [],
      loading: false,
      finished: false,
      page: 1, // 页码
      perPage: 20,
      error: false
    }
  },
  computed: {},
  watch: {},
  created () { },
  mounted () { },
  methods: {
    async onLoad () {
      try {
        // 1. 请求数据
        const { data } = await getSearchResult({
          page: this.page, // 页码
          per_page: this.perPage, // 每页大小
          q: this.searchText // 搜索关键字
        })
        // 2. 添加到表
        const results = data.data.results
        this.list.push(...results)
        // 3. 设置加载结束
        this.loading = false
        // 4. 判断数据是否加载完毕
        if (results.length) {
          this.page++ // 更新下一页数据
        } else {
          this.finished = true // 没有数据
        }
      } catch (err) {
        this.loading = false
        this.error = true
      }
    }
  }
}
</script>

<style scoped lang="less"></style>
